const express = require('express')
const checkToken = require('./middleware')
const Mock = require('mockjs')
const path = require('path')
const fs = require('fs')

const multer = require('multer')
// const upload = multer({dest: 'uploads/'})
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/')
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, file.fieldname + '-' + uniqueSuffix)
  }
})
const upload = multer({storage})

const app = express()
app.listen(9000, () => {
  console.log('http://localhost:9000')
})


app.post('/api/uploadChunkFile', upload.single('chunk'), (req, res) => {
  let updirPath = path.resolve('uploads')
  // 得到生成目录的名称
  let dirname = req.body.filename.split('_').shift()
  // 判断当前目录下面有没有此目录
  if (!fs.existsSync(path.join(updirPath, dirname))) {
    fs.mkdirSync(path.join(updirPath, dirname))
  }

  const oldFilepath = path.resolve(req.file.path)
  const newFilepath = path.join(path.dirname(oldFilepath), dirname, req.body.filename)
  // 重命名  同步
  fs.renameSync(oldFilepath, newFilepath)
  res.send({
    code: 0,
    msg: 'ok',
    data: {
      path: `http://localhost:9000/${req.body.filename}`
    }
  })
})

app.get('/api/mergeChunkFile', (req, res) => {
  let hash = req.query.hash || ''
  let extName = req.query.ext || ''
  let updirPath = path.resolve('uploads', hash)
  const newFilePath = updirPath + '.' + extName
  // 如果文件不存在，则创建，文件内容为一个buffer
  !fs.existsSync(newFilePath) ? fs.writeFileSync(newFilePath, Buffer.from('')) : null

  if (!fs.existsSync(updirPath)) {
    res.send({
      code: 1000,
      msg: '没有此目录',
      data: null
    })
    return;
  }
  // 读取目录下面的文件列表
  let dirs = fs.readdirSync(updirPath)
  // 升序 从0开始
  dirs.sort((a, b) => {
    let n1 = +a.match(/\w+\_(\d+)\.\w+$/)[1]
    let n2 = +b.match(/\w+\_(\d+)\.\w+$/)[1]
    return n1 - n2
  })
  for (let i = 0; i < dirs.length; i++) {
    let filename = dirs[i];
    const readFilePath = path.join(updirPath, filename)
    // 追加
    fs.appendFileSync(newFilePath, fs.readFileSync(readFilePath))
    // 删除文件
    fs.unlinkSync(readFilePath)
  }
  // 递归删除目录[文件夹]
  fs.rmSync(updirPath, {recursive: true})
  res.send({
    code: 0,
    msg: 'ok',
    data: {
      path: `http://localhost:9000/${req.query.hash}.${extName}`
    }
  })


})
